package com.wxh.multithread;

/**
 * @ClassName: RabbitTortoiseRace
 * @Description: 兔子和乌龟比赛
 * @Author wxh
 * @Date: 2021/12/24 15:47
 * @Version V1.0.0
 * @Since 1.8
 */
public class RabbitTortoiseRace implements Runnable {
    /**
     *  胜利者
     */
    private static String winner;
    private static int step_100 = 100;

    public static void main(String[] args) {
        RabbitTortoiseRace race = new RabbitTortoiseRace();

        // 创建两个线程并启动线程
        new Thread(race, "兔子").start();
        new Thread(race, "乌龟").start();
    }

    @Override
    public void run() {
        for (int i = 0; i <= step_100; i++) {

            // 模拟兔子休息
            if(Thread.currentThread().getName().equals("兔子") && i%10 == 0 ){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


            boolean stopFlag = raceOver(i);
            if(stopFlag){
                // 比赛结束，终止循环
                break;
            }


            System.out.println(Thread.currentThread().getName() + "--> 跑了" + i + "步");
        }
    }

    /**
     * 根据步数比赛是否结束
     * @param step
     * @return boolean
     */
    public boolean raceOver(int step){
        if(winner != null){
            // 说明winner已经赋值
            return true;
        }else{
            if(step >= step_100){
                winner = Thread.currentThread().getName();
                System.out.println("winner is " + winner);
                return true;
            }
        }
        return false;
    }
}
